package ucuserslogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/usercenter"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddOrUpdateUserPayAccountLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddOrUpdateUserPayAccountLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddOrUpdateUserPayAccountLogic {
	return &AddOrUpdateUserPayAccountLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 新增保存或更新用户支付账户
func (l *AddOrUpdateUserPayAccountLogic) AddOrUpdateUserPayAccount(in *pb.AddOrUpdateUserPayAccountReq) (*pb.AddOrUpdateUserPayAccountResp, error) {
	defer utils.RecoverPanic()

	var upa *usercenter.UserPayAccountAddress
	if in.Id <= 0 {
		upa = &usercenter.UserPayAccountAddress{
			Uid:            in.Uid,
			BankCode:       in.BankCode,
			BankCardNumber: in.BankCardNumber,
			BankName:       in.BankName,
			AccountType:    in.AccountType,
			AccountName:    in.AccountName,
			Remark:         in.Remark,
		}
		// 新增
		_, err := l.svcCtx.UserPayAccountAddressModel.Insert(l.ctx, upa)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
	} else {
		var err error
		upa, err = l.svcCtx.UserPayAccountAddressModel.FindOne(l.ctx, in.Id)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
		if in.BankCode != "" {
			upa.BankCode = in.BankCode
		}
		if in.BankCardNumber != "" {
			upa.BankCardNumber = in.BankCardNumber
		}
		if in.BankName != "" {
			upa.BankName = in.BankName
		}
		if in.AccountType != 0 {
			upa.AccountType = in.AccountType
		}
		if in.AccountName != "" {
			upa.AccountName = in.AccountName
		}
		if in.Remark != "" {
			upa.Remark = in.Remark
		}
		// 更新
		err = l.svcCtx.UserPayAccountAddressModel.Update(l.ctx, upa)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, err
		}
	}

	return &pb.AddOrUpdateUserPayAccountResp{}, nil
}
